﻿using Dapper;
using Org.BouncyCastle.Crypto;
using ProTrack.Entity;
using ProTrack.IRepository;
using ProTrack.IServices.ProductProcess;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Threading.Tasks;

namespace ProTrack.Services.ProductProcess
{
    /// <summary>
    /// 工艺流程业务逻辑层
    /// </summary>
    public class ProRouteServices : IProRouteServices
    {
        public ProRouteServices(IBaseRepository db, IBaseConnection baseConnection)
        {
            DB = db;
            BaseConnection = baseConnection.GetConn();
        }
        private IBaseRepository DB { get; }
        private SqlConnection BaseConnection { get; }
        public async Task<bool> AddAsync(ProRoute model, List<ProRouteProcess> list, List<ProRouteProduct> list2, string InnerFieldName = "RouteId")
        {
            var result = await DB.InsertIdentityTranAsync(model, list, list2, InnerFieldName: InnerFieldName);
            return result;
        }

        public async Task<bool> DeleteAsync(int[] Ids)
        {
            if (BaseConnection.State != ConnectionState.Open)
            {
                BaseConnection.Open();
            }
            using (IDbTransaction tran = BaseConnection.BeginTransaction())
            {
                try
                {
                    string sql = @"
                                delete ProRouteProcess where RouteId in (select Id from ProRoute where Id in @Ids);
                                delete ProRouteProduct where RouteId in (select Id from ProRoute where Id in @Ids);
                                delete ProRoute where Id in @Ids;";
                    var result = await BaseConnection.ExecuteAsync(sql, new { Ids }, transaction: tran);
                    tran.Commit();
                    return result > 0;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    throw ex;
                }
            }
        }

        public async Task<bool> DeleteAsync(int Id)
        {
            if (BaseConnection.State != ConnectionState.Open)
            {
                BaseConnection.Open();
            }
            using (IDbTransaction tran = BaseConnection.BeginTransaction())
            {
                try
                {
                    string sql = @"
                                delete ProRouteProcess where RouteId in (select Id from ProRoute where Id = @Id);
                                delete ProRouteProduct where RouteId in (select Id from ProRoute where Id = @Id);
                                delete ProRoute where Id = @Id;";
                    var result = await BaseConnection.ExecuteAsync(sql, new { Id }, transaction: tran);
                    tran.Commit();
                    return result > 0;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    throw ex;
                }
            }
        }

        public async Task<IEnumerable<ProRoute>> GetAllAsync()
        {
            string sql = "select * from ProRoute";
            var list = await DB.QueryAllAsync<ProRoute>(sql);
            return list;
        }

        public async Task<IEnumerable<ProRoute>> GetAsync(int PageIndex, int PageSize, string RouteCode, string RouteName, string EnableFlag)
        {
            string sql = "select * from ProRoute where 1=1";
            if (!string.IsNullOrEmpty(RouteCode))
            {
                sql += " and RouteCode like @RouteCode";
            }
            if (!string.IsNullOrEmpty(RouteName))
            {
                sql += " and RouteName like @RouteName";
            }
            if (!string.IsNullOrEmpty(EnableFlag))
            {
                sql += " and EnableFlag like @EnableFlag";
            }
            sql += " order by CreateTime desc offset @PageSize*(@PageIndex-1) row fetch next @PageSize rows only";
            var list = await DB.QueryAsync<ProRoute>(sql, new { PageIndex, PageSize, RouteCode = $"%{RouteCode}%", RouteName = $"%{RouteName}%", EnableFlag = $"%{EnableFlag}%" });
            return list;
        }

        public async Task<int> GetCountAsync(string RouteCode, string RouteName, string EnableFlag)
        {
            string sql = "select count(*) from ProRoute where 1=1";
            if (!string.IsNullOrEmpty(RouteCode))
            {
                sql += " and RouteCode like @RouteCode";
            }
            if (!string.IsNullOrEmpty(RouteName))
            {
                sql += " and RouteName like @RouteName";
            }
            if (!string.IsNullOrEmpty(EnableFlag))
            {
                sql += " and EnableFlag like @EnableFlag";
            }
            var count = await DB.GetRecoreCountAsync(sql, new { RouteCode = $"%{RouteCode}%", RouteName = $"%{RouteName}%", EnableFlag = $"%{EnableFlag}%" });
            return count;
        }
        public async Task<IEnumerable<ProRouteProcess>> GetProRoutebyIdAsync(string RouteId)
        {
            var list = await DB.QueryAsync<ProRouteProcess>("select  * from ProRouteProcess where RouteId = @RouteId", new { RouteId });
            return list;
        }
        public async Task<IEnumerable<ProRouteProduct>> GetProRouteProductbyIdAsync(string RouteId)
        {
            var list = await DB.QueryAsync<ProRouteProduct>("select  * from ProRouteProduct where RouteId = @RouteId", new { RouteId });
            return list;
        }
        public async Task<bool> GetProRouteProductisBool(string ItemId)
        {
            var result = await DB.GetRecoreCountAsync("select  * from ProRouteProduct where ItemId = @ItemId", new { ItemId });
            return result > 0;
        }
        public async Task<bool> UpdateAsync(ProRoute model, List<ProRouteProcess> list, List<ProRouteProduct> list2, string InnerFieldName = "RouteId")
        {
            var result = await DB.UpdateIdentityTranAsync(model, list, list2, InnerFieldName: InnerFieldName);

            return result;
        }
    }
}
